<template>
  <view
    class="swiper-pia"
    :style="[
      {
        backgroundColor:
          commentlist.length > 0 ? 'rgba(238, 238, 238, 1)' : '#fff',
      },
      { height: commentlist.length > 0 ? 'auto' : '100vh' },
    ]"
  >
    <cu-custom bgColor="bgcolorfff" :isBack="true">
      <block slot="content" class="toptext"></block>
    </cu-custom>
    <!-- 顶部title -->
    <view class="pic-title">
      <text>{{ name }}</text>
      <text>{{ summary }}</text>
    </view>

    <view class="swiper-wrapper">
      <view
        class="item"
        :class="imageDataList[index].className"
        :animation="getAnimation(index)"
        v-for="(item, index) in list"
        :key="index"
        :style="{
          backgroundImage: `url(${item.cover.fileUrl})`,
        }"
        @touchstart="touchStart"
        @touchend="touchEnd($event, index + 1)"
        @click="handelSelectCard(index, item.id, item.contentSubType)"
      >
        <view class="heart_box">
          <heart
            :value="item.favorite.isFavorite"
            :item="item"
            @handel="handelHeart"
          ></heart>
        </view>
      </view>
    </view>
    <image
      :src="
        'https://static.77du.net/template/ciff/img/hartgif.gif?id=' +
        Math.random()
      "
      @click.stop
      v-if="showLikeGif"
      class="showLikeGift"
      style="width: 750rpx; height: 750rpx;"
    />

    <!-- 进度条 -->

    <view class="progress">
      <view
        :animation="transitionMoveX"
        :style="'width:' + progress + 'rpx'"
      ></view>
    </view>

    <view class="kong_photo" v-if="commentlist.length > 0"></view>

    <!-- <view class="tuji" v-if="commentlist.length > 0">
      <text>相关图集</text>
      <scroll-view
        class="tuji_sco"
        :scroll-x="true"
        :enable-flex="true"
        :scroll-anchoring="true"
      >
        <view v-for="(item, index) in commentlist" :key="index">
          <view class="tuji_box">
            <image src="" alt mode="widthFix" />
            <text>本日新品推荐</text>
          </view>
        </view>
      </scroll-view>
    </view> -->

    <view class="kong_foot"></view>
    <Prompt v-model="authSwitch"></Prompt>
  </view>
</template>

<script>
import heart from "../../conpoments/heart";
import { getSpacialData, recommendNew } from "../../api/api";
import { collectSpacial, cancelSpacial } from "../../api/api";
export default {
  data() {
    return {
      list: [], //卡片数组 注意小于5可能会出现问题
      imageDataList: [], //动画数组
      direction: "left",
      moving: false,
      height: uni.getSystemInfoSync().windowHeight,
      width: uni.getSystemInfoSync().windowWidth,
      lastTime: 0,
      currentIndex: 0,
      showLikeGif: false,
      transitionMoveX: {},
      id: "",
      cardlist: true, //卡片的长度是否足够5
      commentlist: [], //推荐列表
      name: "",
      summary: "",
    };
  },
  computed: {
    progress() {
      if (this.list) {
        // this.cardlist
        return 660 / this.list.length;
      } else {
        return 0;
      }
    },
    transition() {
      return this.progress * (this.currentIndex - 1);
    },
    selectIndex() {
      if (this.currentIndex == this.list.length) {
        return 0;
      } else {
        return this.currentIndex;
      }
    },
  },
  async onLoad({ id }) {
    this.id = id;
    try {
      const res = await getSpacialData(this.id);
      if (res[1].data.code == "000000") {
        const { contents, name, summary } = res[1].data.data;
        this.list = contents;
        this.name = name;
        this.summary = summary;
      }
    } catch (error) {}
    this.initImageDataList();
    try {
      //底部推荐数据
      let res = await recommendNew(this.id);
      if (res[1].data.code === "000000") {
        const { list } = res[1].data;
        this.commentlist = list;
      }
    } catch (error) {}
    // this.list = list
  },
  components: {
    heart,
  },
  methods: {
    initImageDataList() {
      const animationDataList = this.initAnimationDataList();
      const imageDataList = this.list.map((item, index) => {
        const className = `p${index + 1}`;
        const animationData = animationDataList[index];

        return {
          className,
          animationData,
        };
      });

      this.imageDataList = imageDataList;
    },
    initAnimationDataList() {
      const animationDataList = [];

      const leftAnimation = uni.createAnimation({
        duration: 600,
        timingFunction: "linear",
        transformOrigin: `${this.width}px ${this.height * 1.8}px 0`,
      });

      leftAnimation.rotate(-40).opacity(0).step();
      const leftAnimationData = leftAnimation.export();

      const rightAnimation = uni.createAnimation({
        duration: 600,
        timingFunction: "linear",
        transformOrigin: `${-this.width}px ${this.height * 1.8}px 0`,
      });

      rightAnimation.rotate(40).opacity(0).step();
      const rightAnimationData = rightAnimation.export();

      animationDataList.push({
        leftAnimationData,
        rightAnimationData,
      });

      this.otherAnimationData({
        opacity: 1,
        scale: 1,
        translateY: 0,
        animationDataList,
      });
      this.otherAnimationData({
        opacity: 0.8,
        scale: 0.94,
        translateY: -10,
        animationDataList,
      });
      this.otherAnimationData({
        opacity: 0.6,
        scale: 0.88,
        translateY: -20,
        animationDataList,
      });

      new Array(this.list.length - 4).fill(null).forEach(() => {
        this.otherAnimationData({
          opacity: 0,
          scale: 0.82,
          translateY: -30,
          animationDataList,
        });
      });

      return animationDataList;
    },
    otherAnimationData({ opacity, scale, translateY, animationDataList }) {
      const animation = uni.createAnimation({
        duration: 600,
        timingFunction: "linear",
        transformOrigin: "50% 0 0",
      });

      animation.opacity(opacity).scale(scale).translateY(translateY).step();

      const animationData = animation.export();

      animationDataList.push({
        leftAnimationData: animationData,
        rightAnimationData: animationData,
      });
    },
    getAnimation(index) {
      if (!this.moving) return {};

      return this.imageDataList[index].animationData[
        `${this.direction}AnimationData`
      ];
    },
    touchStart(e) {
      this.startX = e.touches[0].clientX;
    },
    touchEnd(e, index) {
      let nowTime = new Date().getTime();
      if (nowTime - this.lastTime > 600) {
        this.lastTime = nowTime;
        const endX = e.changedTouches[0].clientX;
        if (this.moving) {
          this.moving = false;
          const last = this.imageDataList.pop();
          this.imageDataList.unshift(last);
          clearTimeout(this.timer);
        }
        if (Math.abs(endX - this.startX) > 40) {
          this.moving = true;
          this.direction = endX - this.startX > 0 ? "right" : "left";
          this.timer = setTimeout(() => {
            this.moving = false;
            const last = this.imageDataList.pop();
            this.imageDataList.unshift(last);
            //进度条动画效果
            this.heartSwitch = false;
            this.currentIndex = index;
            console.log(index);
            this.createdAnimatedProgress(index);
          }, 320);
        }
      }
    },
    handelSelectCard() {
      let contype = this.list[this.selectIndex].contentSubType;
      let contentId = this.list[this.selectIndex].contentId;
      console.log(contentId);
      console.log(contype);
      let url = "";
      if (contype == 2) {
        url = `/pages/article/article?id=${contentId}&token=${
          uni.getStorageInfoSync("userInfo").token
        }`;
      } else if (contype == 3) {
        //图集
        url = "/pages/photo/photo?id=" + contentId;
      } else if (contype == 5) {
        //视频
        url = "/pages/video/video?id=" + contentId;
      }
      uni.navigateTo({
        url,
      });
    },
    createdAnimatedProgress(index) {
      //图片数据在编号的时候，索引排序从1开始
      let animation = uni.createAnimation({
        transformOrigin: "50% 50%",
        duration: 600,
        timingFunction: "ease",
        delay: 0,
      });
      this.transitionMoveX = animation;
      animation.translateX((this.transition / 750) * this.width).step();
      this.transitionMoveX = animation.export();
    },
    handelHeart(state) {
      if (!this.AuthState()) return;
      if (state) {
        this.showLikeGif = true;
        collectSpacial(this.list[this.selectIndex].id).then((res) => {});
        setTimeout(() => {
          this.showLikeGif = false;
        }, 2000);
      } else {
        cancelSpacial(this.list[this.selectIndex].id).then((res) => {});
      }
      this.list[this.selectIndex].favorite.isFavorite = state;
    },
  },
};
</script>

<style lang="stylus" scoped>

.swiper-wrapper
    position relative
    width 640rpx
    height 740rpx
    margin 100rpx auto 0
    >image
        position absolute
        left 0
        top 0
        width 100%
        height 100%
        z-index 9999
    .item
        position absolute
        left 0
        top 0
        width 100%
        height 100%
        background-repeat no-repeat
        background-size cover
        background-position center center
        z-index 1
        opacity 0
        transform-origin: center 0
        transform: scale(1) translateY(-48rpx)
        border-radius:20rpx
        box-shadow: 0px 30rpx 30rpx -30rpx #5E5E5E
        .heart_box
          position: absolute;
          z-index: 99999;
          right: 46rpx;
          bottom: 43rpx;
    .p1
        opacity 1
        z-index 5
        transform: scale(1) translateY(0)
    .p2
        opacity 0.8
        z-index 4
        transform: scale(0.94) translateY(-16rpx)
    .p3
        opacity 0.6
        z-index 3
        transform: scale(0.88) translateY(-32rpx)
    .p4
        opacity 0
        z-index 2
        transform: scale(0.82) translateY(-48rpx)
</style>

<style lang="scss" scoped>
.swiper-pia {
  width: 100%;
  overflow: hidden;
  background-color: #ffffff;
  position: fixed;
  top: 0;
  left: 0;
}
.pic-title {
  margin-top: 60rpx;
  display: flex;
  flex-direction: column;
  padding-left: 40rpx;
  > text {
    font-family: Source Han Sans CN;
    color: rgba(74, 74, 74, 1);
    &:first-child {
      font-size: 48rpx;
      font-weight: 800;
      color: rgba(74, 74, 74, 1);
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
    &:last-child {
      margin-top: 27rpx;
      font-size: 28rpx;
      font-weight: 400;
      height: 40rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
  }
}

.progress {
  width: 660rpx;
  height: 15rpx;
  background: rgba(238, 238, 238, 1);
  border-radius: 8rpx;
  margin: 0 auto;
  margin-top: 86rpx;
  position: relative;
  > view {
    height: 15rpx;
    background: rgba(255, 0, 0, 1);
    box-shadow: 0px 0px 8rpx 0px rgba(255, 76, 89, 0.89);
    border-radius: 8rpx;
  }
}

.kong_photo {
  width: 750rpx;
  height: 14rpx;
  background: rgba(248, 248, 248, 1);
  margin-top: 108rpx;
}

.tuji {
  padding-top: 51rpx;
  > text {
    font-size: 32rpx;
    font-family: Source Han Sans CN;
    font-weight: 500;
    color: rgba(36, 36, 36, 1);
    display: block;
    padding-left: 40rpx;
  }
  .tuji_sco {
    width: 100%;
    margin-top: 45rpx;
    display: flex;
    flex-wrap: nowrap;
    max-height: 435rpx;
    .tuji_box {
      width: 271rpx;
      border-radius: 10rpx;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      justify-content: flex-start;
      border-radius: 10rpx;
      overflow: hidden;

      &:first-child {
        margin-left: 40rpx;
      }
      > image {
        width: 100%;
        min-height: 380rpx;
      }
      > text {
        margin-top: 25rpx;
        font-size: 26rpx;
        font-family: PingFang SC;
        font-weight: bold;
        color: rgba(36, 36, 36, 1);
        text-indent: 5rpx;
      }
    }
  }
}

.kong_foot {
  height: 103rpx;
}

.blink {
  width: 100px;
  height: 100px;
  background: url("../../static/img/heart.png") no-repeat;
  background-position: 0 0;
  transition: background-position 1s steps(28);
  transition-duration: 0s;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: -10;
  opacity: 0;
  &.is_active {
    opacity: 1;
    z-index: 999;
    -webkit-transition-duration: 1s;
    transition-duration: 1s;
    background-position: -2800px 0;
  }
}
</style>
